<?php
/**
 * Created by PhpStorm.
 * User: liuchaozhong
 * Date: 2018/8/20
 * Time: 上午10:36
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Comments extends Model
{
    protected $table = 'comments';
    public $timestamps = false;
    public $fillable = ['member_id','article_id','content','date','comment_id'];
    public $status_arr = ['显示', '隐藏'];
    //评论关联用户
    public function g_member()
{
    return $this->belongsTo(Member::class, 'member_id');
}
    //批量审核
    public function check($ids, $status)
    {
        if($status == 1){
            $update = ['status'=>1];
        }elseif($status == 0){
            $update = ['status'=>0];
        }
        $sql = Comments::select('article_id','status')->whereIn('id', $ids)->get();
        $arr = [];
        if($status == 1) {
            foreach ($sql as $k => $v) {
                if ($v->status == 0) {
                    array_push($arr, $v->article_id);
                }
            }
        }elseif($status == 0){
            foreach ($sql as $k => $v) {
                if ($v->status == 1) {
                    array_push($arr, $v->article_id);
                }
            }
        }
        try {
            $res = Comments::whereIn('id',$ids)->update($update);
        }catch (\Exception $e) {
            $res = false;
        }
        $model = Comments::select(DB::raw('count(*) as nums, article_id'))->whereIn('article_id', $arr)->where('status', 0)->groupBy('article_id')->get();
        foreach($model as $k=>$v){
            $updated = ['comments_num' => $v->nums];
            Article::where('id', $v->article_id)->update($updated);
        }
        return $res ? $res : false;
    }
}